package com.link.linkupjavaweb.controller.admin;

import com.link.linkupjavaweb.common.Constants;
import com.link.linkupjavaweb.common.Result;
import com.link.linkupjavaweb.entity.Admin;
import com.link.linkupjavaweb.mapper.GameRecordMapper;
import com.link.linkupjavaweb.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 管理员数据统计Controller
 */
@Controller
@RequestMapping("/admin")
public class AdminStatsController {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private GameRecordMapper gameRecordMapper;
    
    /**
     * 管理员主页（包含统计面板）
     */
    @GetMapping("/home")
    public String home(HttpSession session, Model model) {
        Admin admin = (Admin) session.getAttribute(Constants.SESSION_ADMIN);
        if (admin == null) {
            return "redirect:/admin/login";
        }
        model.addAttribute("admin", admin);
        return "admin/home";
    }
    
    /**
     * 获取管理员统计数据（API）
     */
    @GetMapping("/stats/data")
    @ResponseBody
    public Result<Map<String, Object>> getStatsData(HttpSession session) {
        try {
            Admin admin = (Admin) session.getAttribute(Constants.SESSION_ADMIN);
            if (admin == null) {
                return Result.error("请先登录");
            }
            
            Map<String, Object> data = new HashMap<>();
            
            // 1. 用户统计
            long totalUsers = userMapper.selectCount(null);
            long activeUsers = userMapper.selectCount(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.link.linkupjavaweb.entity.User>()
                    .eq("status", 0)
            );
            long onlineUsers = userMapper.selectCount(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.link.linkupjavaweb.entity.User>()
                    .in("online_status", 1, 2)
            );
            
            data.put("totalUsers", totalUsers);
            data.put("activeUsers", activeUsers);
            data.put("onlineUsers", onlineUsers);
            data.put("disabledUsers", totalUsers - activeUsers);
            
            // 2. 游戏统计
            long totalGames = gameRecordMapper.selectCount(null);
            long singleGames = gameRecordMapper.selectCount(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.link.linkupjavaweb.entity.GameRecord>()
                    .eq("game_type", 1)
            );
            long battleGames = gameRecordMapper.selectCount(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.link.linkupjavaweb.entity.GameRecord>()
                    .eq("game_type", 2)
            );
            
            data.put("totalGames", totalGames);
            data.put("singleGames", singleGames);
            data.put("battleGames", battleGames);
            
            // 3. 积分统计
            com.link.linkupjavaweb.entity.User topUser = userMapper.selectOne(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<com.link.linkupjavaweb.entity.User>()
                    .eq("status", 0)
                    .orderByDesc("total_score")
                    .last("LIMIT 1")
            );
            
            long totalScore = 0;
            java.util.List<com.link.linkupjavaweb.entity.User> allUsers = userMapper.selectList(null);
            for (com.link.linkupjavaweb.entity.User user : allUsers) {
                totalScore += user.getTotalScore();
            }
            
            data.put("totalScore", totalScore);
            data.put("maxScore", topUser != null ? topUser.getTotalScore() : 0);
            data.put("topPlayer", topUser != null ? topUser.getNickname() : "暂无");
            
            // 4. 今日统计（简化版，实际应该查询今日数据）
            long todayNewUsers = 0; // 这里简化处理
            long todayGames = 0;
            
            data.put("todayNewUsers", todayNewUsers);
            data.put("todayGames", todayGames);
            
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取统计数据失败：" + e.getMessage());
        }
    }
}

